# -*- encoding : utf-8 -*-
# 下载数据

require 'net/http'
require 'fileutils'
require 'open-uri'


class Remember

  attr_reader :name

  def initialize(name='first')
    @name = name
  end

  def self.download(dir, file_name, url)
    unless File.directory?(dir)
      FileUtils.mkdir_p(dir)
    end
    retry_count = 0
    begin
      yield(dir, file_name, url)
    rescue Timeout::Error
      puts "下载 #{url} 超时"
      retry_count += 1
      if retry_count <= 3
        retry
      end
    rescue Errno::ECONNRESET
      puts "下载 #{url} 错误"
      retry_count += 1
      if retry_count <= 3
        sleep(10)
        retry
      end
    rescue => e
      puts "#{e.inspect}"
      retry_count += 1
      if retry_count <= 3
        retry
      end
    end
    if retry_count < 4
      puts "下载 #{url} 完成"
      return true
    else
      puts "下载 #{url} 失败"
      return false
    end
  end

  def self.image_download(dir, file_name, url, interval=0)
    download(dir, file_name, url) do |directory, filename, uri|
      File.open(File.join(directory, filename), "wb") { |s|
        res = Net::HTTP.get(URI.parse(URI.encode(uri.strip)))
        s.write(res)
        sleep interval
      }
    end
  end

  def self.file_download(dir, file_name, url, interval=0)
    download(dir, file_name, url) do |directory, filename, uri|
      open(uri) do |fin|
        open(File.join(directory, filename), 'wb') do |fout|
          while(buf = fin.read(256))
            fout.write buf
            sleep interval
          end
        end
      end
    end
  end

end
